package cn.dyw.shop.mapping;

import cn.dyw.shop.json.Json;
import cn.dyw.shop.model.Goods;
import cn.dyw.shop.model.ShoppingCart;
import cn.dyw.shop.model.User;
import cn.dyw.shop.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author: dyw770
 * @date: 2018/5/6
 */
@Controller
@RequestMapping("/shoppingCart")
public class ShoppingCartMapping extends BaseMapping<ShoppingCart> {

    @Autowired
    protected void setBaseService(ShoppingCartService shoppingCartService) {
        this.baseService = shoppingCartService;
    }

    /**
     * 添加到购物车
     */
    @ResponseBody
    @RequestMapping("/add")
    public Json addToCart(HttpSession session, @RequestParam("id") Integer id, @RequestParam("num") Integer num) {
        User user = (User) session.getAttribute("user");
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setCreateTime(new Date());
        Goods goods = new Goods();
        goods.setId(id);
        shoppingCart.setGoods(goods);
        shoppingCart.setNum(num);
        shoppingCart.setUser(user);
        baseService.save(shoppingCart);
        return Json.factory(shoppingCart, true, 1001, "success");
    }

    /**
     * 添加到购物车
     */
    @ResponseBody
    @RequestMapping("/update")
    public Json updateCart(@RequestParam("id") Integer id, @RequestParam("num") Integer num) {
        ShoppingCart shoppingCart = ((ShoppingCartService) baseService).updateCart(id, num);
        return Json.factory(shoppingCart, true, 1001, "success");
    }

    /**
     * 查询购物车中的所有数据
     * @param session
     * @return
     */
    @ResponseBody
    @GetMapping("/find/car/all")
    public Json findAll(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<ShoppingCart> all = ((ShoppingCartService) baseService).findByUserId(user.getId());
        return Json.factory(all, true, 1001, "success");
    }

    /***
     * 删除
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/find/delete")
    public Json delete(Integer id) {
        baseService.delete(id);
        return Json.factory(null, true, 1001, "success");
    }

    /***
     * 清空购物车
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/find/delete/all")
    public Json deleteAll(HttpSession session) {
        User user = (User) session.getAttribute("user");
        ((ShoppingCartService) baseService).deleteAll(user.getId());
        return Json.factory(null, true, 1001, "success");
    }
}
